package com.etoak.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.etoak.common.jwt.JwtUtil;
import com.etoak.common.redis.RedisService;
import com.etoak.common.web.exception.CustomException;
import com.etoak.entity.User;
import com.etoak.entity.dto.LoginDTO;
import com.etoak.entity.vo.TokenVO;
import com.etoak.mapper.UserMapper;
import com.etoak.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author et2406
 * @since 2024-11-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    RedisService redisService;

    public static final String KEY = "code:";

    @Override
    public TokenVO login(LoginDTO loginDTO) {
        /* 判断验证码 */
        String savedCode = redisService.get(KEY + loginDTO.getUuid());
        if (!StringUtils.equalsIgnoreCase(savedCode, loginDTO.getCode())) {
            throw new CustomException("验证码错误或已过期");
        }

        /* 校验用户名和密码 */
        String password = MD5.create().digestHex(loginDTO.getPassword());
        User one = lambdaQuery().eq(User::getUsername, loginDTO.getUsername())
                .eq(User::getPassword, password).one();
        if(ObjectUtils.isEmpty(one)){
            throw new CustomException("用户名或者密码错误");
        }
        /* 创建Token */
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",one.getUsername());
        claims.put("id",one.getId());

        String token = JwtUtil.create(claims);
        return new TokenVO(one.getUsername(),token);
    }
}
